package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"yh/cache"
	"yh/models"
)

type UserController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	var user models.User
	models.DB.Debug().Where("username=?", username).Find(&user)
	key := "login" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = Res{
			Code: 500,
			Data: nil,
			Msg:  "密码错误三次,封禁10分钟",
		}
		c.ServeJSON()
		return
	}
	if user.Password != password {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Minute*10)
		}
		c.Data["json"] = Res{
			Code: 500,
			Data: nil,
			Msg:  "密码错误",
		}
		c.ServeJSON()
		return
	}
	models.DB.Debug().Find(&user)
	c.Data["json"] = Res{
		Code: 200,
		Data: nil,
		Msg:  "登陆成功",
	}
	c.ServeJSON()
	return
}
